package cn.zjitc.exam.dao.impl;

import cn.zjitc.exam.dao.ProductDao;
import cn.zjitc.exam.domain.Product;
import cn.zjitc.exam.util.DruidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository("productDao")
public class ProductDaoImpl implements ProductDao {
    @Autowired
    private JdbcTemplate jdbcTemplate ;

    @Override
    public List<Product> findAll() {
        String sql = "select * from product";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class));
    }

    @Override
    public Product findById(int id) {
        try {
            String sql = "select * from product where id = ?";
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Product.class), id);
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public boolean update(Product product) {
        String sql = "update product set name = ?,price = ?,description = ?,stock = ?,create_time = ?,create_by = ? where id = ?";
        int update = jdbcTemplate.update(sql, product.getName(), product.getPrice(), product.getDescription(), product.getStock(), product.getCreateTime(), product.getCreateBy(), product.getId());
        return update > 0;
    }

    @Override
    public boolean delete(int id) {
        String sql = "delete from product where id = ?";
        int update = jdbcTemplate.update(sql, id);
        return update > 0;
    }

    @Override
    public boolean add(Product product) {
        String sql = "insert into product (name,price,description,stock,create_by) values(?,?,?,?,?)";
        int update = jdbcTemplate.update(sql, product.getName(), product.getPrice(), product.getDescription(), product.getStock(), product.getCreateBy());
        return update > 0;
    }

    @Override
    public int getTotalCount() {
        String sql = "select count(*) from product";
        return jdbcTemplate.queryForObject(sql, Integer.class);
    }

    @Override
    public List<Product> findByPage(int start, int pageSize) {
        String sql = "select * from product limit ?,?";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Product.class), start, pageSize);
    }
}
